var http = require("http")
var fs = require('fs')
var AipFaceClient = require("baidu-aip-sdk").face
var express = require('express')
var app = express()
var path = require('path')
var sd = require('silly-datetime')
var User = require('./users/user')

//Set the ejs template engine
app.set('view engine','ejs')
app.set('views','ejsViews')


var CronJob = require('cron').CronJob
// Set APPID/AK/SK
var APP_ID = "16697846";
var API_KEY = "96htwMaT7FmDQlaqka644Q84";
var SECRET_KEY = "Yoar7jRsXr44O3j4ers8trT4PZ44fSy0";

// Create a new object, it is recommended to save only one object to call the service interface
var client = new AipFaceClient(APP_ID, API_KEY, SECRET_KEY);


var HttpClient = require("baidu-aip-sdk").HttpClient;

// 设置request库的一些参数，例如代理服务地址，超时时间等
// request参数请参考 https://github.com/request/request#requestoptions-callback
HttpClient.setRequestOptions({timeout: 5000});

// 也可以设置拦截每次请求（设置拦截后，调用的setRequestOptions设置的参数将不生效）,
// 可以按需修改request参数（无论是否修改，必须返回函数调用参数）
// request参数请参考 https://github.com/request/request#requestoptions-callback
HttpClient.setRequestInterceptor(function(requestOptions) {

    requestOptions.timeout = 5000;
   
    return requestOptions;
});

app.use('/node_modules/',express.static(path.join(__dirname,'./node_modules')))
app.use('/public/',express.static(path.join(__dirname,'./public/')))
app.engine('html',require('express-art-template'))

new CronJob('*/1 * * * * *', function() {


    var url = "http://192.168.0.103:8080/?action=snapshot";

    http.get(url, function(res){
        var imgData = "";
    
        res.setEncoding("binary"); //Be sure to set the response code to binary or the downloaded image will not open.
    
    
        res.on("data", function(chunk){
            imgData+=chunk;
        });
    
        res.on("end", function(){
            fs.writeFile("./public/img/logonew.jpg", imgData, "binary", function(err){
                if(err){
                    console.log("down fail");
                }
                console.log("down success");
            });
        });
    });
    
   //------------------------------------------
   


       

        
            // res.render('index.html')
            var image = fs.readFileSync("./public/img/logonew.jpg").toString("base64")

            var imageType = "BASE64";
        
            var groupIdList = "eng2";

            client.search(image, imageType, groupIdList).then(function(result) {
                var id = result.result.user_list
            
                var user_id = id.map(v =>{return v. user_id}).join()
                 //If the face recognition is successful, the name will be printed.
                console.log(user_id)
                 //Convert user to database format
                
                var o = new User()
                o.Name = user_id

                var conditions = {Name : o.Name,Department: o.Department,Status: o.Status,Image: o.Image};
                var time = {Created_time: sd.format(new Date(), 'YYYY-MM-DD HH:mm:ss')}
                User.findOneAndUpdate(conditions,time,{upsert:true},function(err,dos){
                    if(err)
                    console.log(err)
                    console.log(dos)
                })

              return code = 1
            }).catch(function(err) {
                    
                    console.log(err)
                    return code = 0
                });
        

        app.get('/',function(req,res){
                res.render('index.ejs')
            })
        

        app.post('/userlist',function(req,res){

            //Recognize the faces and update the database to find all the recognition results in the database in chronological order.
            User.find().sort({Created_time:1}).exec(function(err,face){
              if(err)
              console.log(err);
              console.log('123');//返回的是一个数组
              res.send({face:face,code:code})
              
          })


      })
     
}, null, true);


 
app.listen(5000,function(){
    console.log('running');
    
})














